//
//  filesManagerVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/7.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "filesManagerVC.h"
#import "MicroDef.h"
#define KSECTIONHEIGHT 20.0f
#import "FileNormalCell.h"
#import "FileOperateCell.h"
#import "CFileModel.h"
#import "ChildHoodService.h"
#import "CFolderMgr.h"
#import "CAccountModel.h"
#import "UIUtil.h"
#import "IMPreviewFileController.h"
#import "IMFowardController.h"
#import "WZNavigationController.h"


@interface filesManagerVC ()<UITableViewDelegate, UITableViewDataSource, FileOperateCellDelegate, UIDocumentInteractionControllerDelegate>
{
    UITableView *_tableView;
}
@property (nonatomic, strong) NSMutableArray *dirArray;
@property (nonatomic, strong) NSMutableArray *filesArray;
@property (nonatomic, strong)  UIDocumentInteractionController *doInter;
@end

@implementation filesManagerVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"我的文件"];
    
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    [self loadFiles];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!IsIOS7) {
        self.navigationController.navigationBar.tintColor = RGBCOLOR(44.0f, 170.0f, 253.0f);
    } else {
        self.navigationController.navigationBar.barTintColor = RGBCOLOR(44.0f, 170, 253.0f);
    }
    
}


- (NSMutableArray *)filesArray
{
    if (_filesArray == nil) {
        _filesArray = [NSMutableArray array];
    }
    return _filesArray;
}

- (NSMutableArray *)dirArray
{
    if (_dirArray == nil) {
        _dirArray = [NSMutableArray array];
    }
    return _dirArray;
}


-(void)loadFiles
{
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *array1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[ChildHoodService defaultService] personalDownloadFilePath] error:nil];
    NSArray *array2 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[ChildHoodService defaultService] groupDownloadFilePath] error:nil];
    for (NSString *subPath in array1) {
        [arrayM addObjectsFromArray:[UIUtil handleFilePathWithPath:[[ChildHoodService defaultService] personalDownLoadFilePathWithUserId:subPath] isGroup:NO]];
    }
    for (NSString *subPath in array2) {
        [arrayM addObjectsFromArray:[UIUtil handleFilePathWithPath:[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:subPath] isGroup:YES]];
    }
    
    [self.filesArray addObjectsFromArray:[arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"CreateDate" ascending:NO]]]];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */




#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return [_filesArray count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 1;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"FileNormalCell";
    static NSString *OperCellIdentifier = @"FileOperateCell";
    UITableViewCell *cell = nil;
    CFileModel *file = _filesArray[indexPath.row];

    if(file.is_opened)
    {
        FileOperateCell  *fileOperCell = [tableView dequeueReusableCellWithIdentifier:OperCellIdentifier];
        if (fileOperCell == nil) {
            fileOperCell = [[[NSBundle mainBundle] loadNibNamed:@"FileOperateCell" owner:self options:nil] objectAtIndex:0];
        }
        [fileOperCell.titleLabel setText:file.FileName];
        fileOperCell.fileOperateCellDelegate = self;
        fileOperCell.indePath = indexPath;
        [fileOperCell.fileIcon setImage:[UIImage imageNamed:[UIUtil getFileIconByName:file.FileName]]];
        //        UIView *backView = [[UIView alloc] init];
        //        [backView setBackgroundColor:[UIColor clearColor]];
        //        [fileOperCell setSelectedBackgroundView:backView];
        fileOperCell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell = fileOperCell;
    }
    else
    {
        FileNormalCell  *fileNormalCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (fileNormalCell == nil) {
            fileNormalCell = [[[NSBundle mainBundle] loadNibNamed:@"FileNormalCell" owner:self options:nil] objectAtIndex:0];
        }
        [fileNormalCell.titleLabel setText:file.FileName];
        if(indexPath.row != [_filesArray count] -1)
        {
            [fileNormalCell.seperatorLine setHidden:NO];
        }
        else
        {
            [fileNormalCell.seperatorLine setHidden:YES];
        }
        fileNormalCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [fileNormalCell.fileIcon setImage:[UIImage imageNamed:[UIUtil getFileIconByName:file.FileName]]];
        cell = fileNormalCell;
    }
    
    
    return cell;
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    title = [_filesArray objectAtIndex:indexPath.row];
    return title;
}


- (void)FileOperateCellDidDelWithIndexPath:(NSIndexPath *)indexPath
{
    CFileModel *fileModel = self.filesArray[indexPath.row];
    [self.filesArray removeObjectAtIndex:indexPath.row];
    [[NSFileManager defaultManager] removeItemAtPath:fileModel.LocalFilePath error:nil];
    [_tableView reloadData];
}
- (void)FileOperateCellDidForwardWithIndexPath:(NSIndexPath *)indexPath
{
    [ChildHoodService defaultService].fileModel = self.filesArray[indexPath.row];
    IMFowardController *foward = [[IMFowardController alloc] init];
     WZNavigationController *nav = [[WZNavigationController alloc] initWithRootViewController:foward];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)FileOperateCellDidOpenWithIndexPath:(NSIndexPath *)indexPath
{
    CFileModel *fileModel = self.filesArray[indexPath.row];
    if ([self checkFileTypeWithFileName:fileModel.FileName]) {
        
        if (fileModel.LocalFilePath.length > 0) {
            UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileModel.LocalFilePath]];
            self.doInter = doInter;
            self.doInter.delegate = self;
            [doInter presentPreviewAnimated:YES];
            
        }
        
        
    } else {
        if (fileModel.LocalFilePath.length > 0) {
            UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:fileModel.LocalFilePath]];
            doInter.delegate = self;
            self.doInter = doInter;
            [doInter presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
            
        }
        
    }


}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application
{
//    NSLog(@"heheheh");
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}


- (BOOL)checkFileTypeWithFileName:(NSString *)fileName
{
    NSString *nameStr = [fileName lowercaseString];
    
    
    NSString *fileIcon = [UIUtil getFileIconByName:nameStr];
    if ([fileIcon isEqualToString:@"othersIcon"] || fileIcon == nil || [fileIcon isEqualToString:@"rarIcon"]) {
        return NO;
    } else {
        return YES;
    }
    
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    CGFloat height = 0;
    switch (section) {
        case 0:
            height = 1;
            break;
        default:
            break;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 0:
            height = 3;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 1);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section != 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 3);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    
    
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 55.0f;
    CFileModel *file = _filesArray[indexPath.row];
    
    if(file.is_opened)
    {
        height = 110.0f;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //    MineFile *file = _filesArray[indexPath.row];
    
    [_filesArray enumerateObjectsUsingBlock:^(CFileModel *obj, NSUInteger idx, BOOL *stop) {
        if (idx == indexPath.row) {
            obj.is_opened = !obj.is_opened;
        } else {
            obj.is_opened = NO;
        }
    }];
    [tableView reloadData];
    
    UITableViewCell *fileCell = [tableView cellForRowAtIndexPath:indexPath];
    if (CGRectGetMaxY(fileCell.frame) > CGRectGetMaxY(tableView.frame) + tableView.contentOffset.y) {
       [tableView setContentOffset:CGPointMake(0, CGRectGetMaxY(fileCell.frame) - tableView.frame.size.height) animated:NO];
    }
//
}


-(void)showAboutVC
{
    
}

-(void)showSettingVC
{
    
}




@end
